<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传demo</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <link rel="stylesheet" href="static/style.css">
</head>
<body>
    <div class="container">
        <h2>文件上传DEMO</h2>
        up pic:<input class="upload-file" type="file" value=""><br/>
        <input class="do-upload" type="button" value="upload" /><br/>
    </div>
    <div class="container">
        <h2>上传预览</h2>
        <div class="preview"></div>
    </div>
    <script src="static/jquery.js"></script>
    <script>
        $('.do-upload').click(function () {
            doUpload();
        });

        // 上传进度更新
        function progressUpdate(e) {
            console.log(e);
        }

        function doUpload() {
            var form_data = new FormData();
            // 把上传的数据放入form_data
            form_data.append("Filedata", $('.upload-file')[0].files[0]);

            var process = $.ajax({
                type: "POST", // 上传文件要用POST
                url: 'upload.php',
                dataType : "json",
                crossDomain: true, // 如果用到跨域，需要后台开启CORS
                processData: false,  // 注意：不要 process data
                contentType: false,  // 注意：不设置 contentType
                data: form_data,
                xhr: function(){ //获取ajaxSettings中的xhr对象，为它的upload属性绑定progress事件的处理函数
                    var myXhr = $.ajaxSettings.xhr();
                    if(myXhr.upload){ //检查upload属性是否存在
                        //绑定progress事件的回调函数
                        myXhr.upload.addEventListener('progress', function (e) {
                            progressUpdate(e);
                        }, false);
                    }
                    return myXhr; //xhr对象返回给jQuery使用
                },
                success: function (data) {
                    if(data.status == 1) {
                        $('.preview').html('<img src="'+data.url+'">');
                    } else {
                        alert(data.msg);
                    }
                }
            }).fail(function(msg) {
                alert('Error:'+msg);
            });
        }
    </script>
</body>